/**
 * 
 */
package ${basepackage}.controller.op;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import com.excalibur.core.util.SpringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import ${basepackage}.controller.basic.DateTimeBinderController;
import ${basepackage}.manager.op.AuthorityManager;
import ${basepackage}.manager.op.OpUserManager;
import ${basepackage}.manager.op.RoleManager;
import ${basepackage}.manager.exception.ServiceException;
import ${basepackage}.model.criteria.op.AuthorityCriteria;
import ${basepackage}.model.criteria.op.OpUserCriteria;
import ${basepackage}.model.criteria.op.RoleCriteria;
import ${basepackage}.model.json.JsonResponse;
import ${basepackage}.model.po.op.Authority;
import ${basepackage}.model.po.op.Role;
import ${basepackage}.model.vo.op.authority.AddAuthorityForm;
import ${basepackage}.model.vo.op.authority.AuthorityRow;
import ${basepackage}.model.vo.op.authority.UpdateAuthorityForm;
import ${basepackage}.model.vo.common.Page;
import ${basepackage}.model.vo.op.opuser.AddOpUserForm;
import ${basepackage}.model.vo.op.opuser.OpUserRow;
import ${basepackage}.model.vo.op.opuser.UpdateOpUserForm;
import ${basepackage}.model.vo.op.role.AddRoleForm;
import ${basepackage}.model.vo.op.role.RoleRow;
import ${basepackage}.model.vo.op.role.UpdateRoleForm;

/**
 * @author "Jiance Qin"
 * 
 * @date 2014年3月10日
 * 
 * @time 下午6:31:17
 * 
 * @desc
 * 
 */
@Controller
@RequestMapping(value = "/opAdmin")
public class OpAdminController extends DateTimeBinderController {

	private final static Logger logger = LoggerFactory
			.getLogger(OpAdminController.class);

	@Autowired
	private OpUserManager opUserManager;
	@Autowired
	private RoleManager roleManager;
	@Autowired
	private AuthorityManager authorityManager;

	/**
	 * 后台用户管理页.
	 * 
	 * @return
	 */
	@RequestMapping(value = "/opuser")
	public String userListPage(ModelMap model) {
		List<Role> roles = new ArrayList<Role>();
		try {
			roles = roleManager.getAllRoles();
		} catch (ServiceException e) {
			logger.error("Failed to get Role info！", e);
			model.put("msg", e.getMessage());
		}
		model.put("roles", roles);
		return "admin/opuser";
	}

	/**
	 * 获取用户列表.
	 * 
	 * @param offset
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/opuser/list")
	@ResponseBody
	public JsonResponse getUserList(int offset, int limit, OpUserCriteria criteria) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		Page<OpUserRow> opUserList = null;
		try {
			opUserList = opUserManager.getOpUsers(criteria, offset, limit);
			jsonResponse.setCode(0);
			jsonResponse.setData(opUserList);
			result = true;
		} catch (ServiceException e) {
			logger.error("Failed to get op user list！", e);
			jsonResponse.setMessage(e.getMessage());
		} catch (DataAccessException e) {
			logger.error("Failed to get op user list！", e);
			jsonResponse.setMessage(SpringUtils
					.getI18nMessage("webapp.controller.sysError"));
		}

		if (!result) {
			jsonResponse.setCode(1);
			opUserList = new Page<OpUserRow>();
			opUserList.setTotal(0L);
			opUserList.setRows(null);
			jsonResponse.setData(opUserList);
		}

		return jsonResponse;
	}

	/**
	 * 获取角色及其权限列表.
	 * 
	 * @param offset
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/opuser/roles")
	@ResponseBody
	public JsonResponse getUserRoleList() {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		List<Role> roleList = null;
		try {
			roleList = roleManager.getAllRoleAuthoes();
			jsonResponse.setCode(0);
			jsonResponse.setData(roleList);
			result = true;
		} catch (ServiceException e) {
			logger.error("Failed to get role and authorities list！", e);
			jsonResponse.setMessage(e.getMessage());
		} catch (DataAccessException e) {
			logger.error("Failed to get role and authorities list！", e);
			jsonResponse.setMessage(SpringUtils
					.getI18nMessage("webapp.controller.sysError"));
		}

		if (!result) {
			jsonResponse.setCode(1);
			roleList = new ArrayList<Role>();
			jsonResponse.setData(roleList);
		}

		return jsonResponse;
	}

	/**
	 * 删除用户.
	 * 
	 * @param offset
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/opuser/delete")
	@ResponseBody
	public JsonResponse deleteUser(Long id) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		try {
			result = opUserManager.delete(id);
			if (result) {
				jsonResponse.setCode(0);
				jsonResponse.setData(id);
			} else {
				jsonResponse.setMessage(SpringUtils
						.getI18nMessage("webapp.controller.sysError"));
			}
		} catch (ServiceException e) {
			logger.error("Failed to delete op user！", e);
			jsonResponse.setMessage(e.getMessage());
		} catch (DataAccessException e) {
			logger.error("Failed to delete op user！", e);
			jsonResponse.setMessage(SpringUtils
					.getI18nMessage("webapp.controller.sysError"));
		}

		if (!result) {
			jsonResponse.setCode(1);
		}
		return jsonResponse;
	}

	/**
	 * 修改用户.
	 * 
	 * @param opUserRow
	 * @return
	 */
	@RequestMapping(value = "/opuser/update")
	@ResponseBody
	public JsonResponse updateUser(@Valid UpdateOpUserForm updateOpUserForm,
			BindingResult validResult) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		// 验证结果检查
		if (validResult.hasErrors()) {
			if (validResult.hasFieldErrors("id")) {
				jsonResponse.setMessage(validResult.getFieldError("id")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("username")) {
				jsonResponse.setMessage(validResult.getFieldError("username")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("realName")) {
				jsonResponse.setMessage(validResult.getFieldError("realName")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("email")) {
				jsonResponse.setMessage(validResult.getFieldError("email")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("tel")) {
				jsonResponse.setMessage(validResult.getFieldError("tel")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("accountDisabled")) {
				jsonResponse.setMessage(validResult.getFieldError(
						"accountDisabled").getDefaultMessage());
			} else if (validResult.hasFieldErrors("accountExpired")) {
				jsonResponse.setMessage(validResult.getFieldError(
						"accountExpired").getDefaultMessage());
			} else if (validResult.hasFieldErrors("accountLocked")) {
				jsonResponse.setMessage(validResult.getFieldError(
						"accountLocked").getDefaultMessage());
			} else if (validResult.hasFieldErrors("credentialsExpired")) {
				jsonResponse.setMessage(validResult.getFieldError(
						"credentialsExpired").getDefaultMessage());
			}
		} else {
			try {
				OpUserRow opUserRow = opUserManager
						.updateOpUser(updateOpUserForm);
				jsonResponse.setCode(0);
				jsonResponse.setData(opUserRow);
				result = true;
			} catch (ServiceException e) {
				logger.error("Failed to update op user！", e);
				jsonResponse.setMessage(e.getMessage());
			} catch (DataAccessException e) {
				logger.error("Failed to update op user！", e);
				jsonResponse.setMessage(SpringUtils
						.getI18nMessage("webapp.controller.sysError"));
			}
		}

		if (!result) {
			jsonResponse.setCode(1);
		}

		return jsonResponse;
	}

	/**
	 * 添加用户.
	 * 
	 * @param opUserRow
	 * @return
	 */
	@RequestMapping(value = "/opuser/add")
	@ResponseBody
	public JsonResponse addUser(@Valid AddOpUserForm addOpUserForm,
			BindingResult validResult) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		// 验证结果检查
		if (validResult.hasErrors()) {
			if (validResult.hasFieldErrors("username")) {
				jsonResponse.setMessage(validResult.getFieldError("username")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("realName")) {
				jsonResponse.setMessage(validResult.getFieldError("realName")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("email")) {
				jsonResponse.setMessage(validResult.getFieldError("email")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("tel")) {
				jsonResponse.setMessage(validResult.getFieldError("tel")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("accountDisabled")) {
				jsonResponse.setMessage(validResult.getFieldError(
						"accountDisabled").getDefaultMessage());
			} else if (validResult.hasFieldErrors("accountExpired")) {
				jsonResponse.setMessage(validResult.getFieldError(
						"accountExpired").getDefaultMessage());
			} else if (validResult.hasFieldErrors("accountLocked")) {
				jsonResponse.setMessage(validResult.getFieldError(
						"accountLocked").getDefaultMessage());
			} else if (validResult.hasFieldErrors("credentialsExpired")) {
				jsonResponse.setMessage(validResult.getFieldError(
						"credentialsExpired").getDefaultMessage());
			}
		} else {
			try {
				OpUserRow opUserRow = opUserManager.addOpUser(addOpUserForm);
				jsonResponse.setCode(0);
				jsonResponse.setData(opUserRow);
				result = true;
			} catch (ServiceException e) {
				logger.error("Failed to add op user！", e);
				jsonResponse.setMessage(e.getMessage());
			} catch (DataAccessException e) {
				logger.error("Failed to add op user！", e);
				jsonResponse.setMessage(SpringUtils
						.getI18nMessage("webapp.controller.sysError"));
			}
		}

		if (!result) {
			jsonResponse.setCode(1);
		}

		return jsonResponse;
	}

	/**
	 * 后台角色管理页.
	 * 
	 * @return
	 */
	@RequestMapping(value = "/role")
	public String roleListPage(ModelMap model) {
		List<Authority> authorities = new ArrayList<Authority>();
		try {
			authorities = authorityManager.getAll();
		} catch (ServiceException e) {
			logger.error("Failed to Authority info！", e);
			model.put("msg", e.getMessage());
		}
		model.put("authorities", authorities);
		return "admin/role";
	}

	/**
	 * 获取角色列表.
	 * 
	 * @param offset
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/role/list")
	@ResponseBody
	public JsonResponse getRoleList(int offset, int limit, RoleCriteria criteria) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		Page<RoleRow> roleList = null;
		try {
			roleList = roleManager.getRoles(criteria, offset, limit);
			jsonResponse.setCode(0);
			jsonResponse.setData(roleList);
			result = true;
		} catch (ServiceException e) {
			logger.error("Failed to get role list！", e);
			jsonResponse.setMessage(e.getMessage());
		} catch (DataAccessException e) {
			logger.error("Failed to get role list！", e);
			jsonResponse.setMessage(SpringUtils
					.getI18nMessage("webapp.controller.sysError"));
		}

		if (!result) {
			jsonResponse.setCode(1);
			roleList = new Page<RoleRow>();
			roleList.setTotal(0L);
			roleList.setRows(null);
			jsonResponse.setData(roleList);
		}

		return jsonResponse;
	}

	/**
	 * 获取所有权限列表.
	 * 
	 * @param offset
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/role/authoes")
	@ResponseBody
	public JsonResponse getRoleAuthorityList() {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		List<Authority> authorityList = null;
		try {
			authorityList = authorityManager.getAll();
			jsonResponse.setCode(0);
			jsonResponse.setData(authorityList);
			result = true;
		} catch (ServiceException e) {
			logger.error("Failed to get authority list！", e);
			jsonResponse.setMessage(e.getMessage());
		} catch (DataAccessException e) {
			logger.error("Failed to get authority list！", e);
			jsonResponse.setMessage(SpringUtils
					.getI18nMessage("webapp.controller.sysError"));
		}

		if (!result) {
			jsonResponse.setCode(1);
			authorityList = new ArrayList<Authority>();
			jsonResponse.setData(authorityList);
		}

		return jsonResponse;
	}

	/**
	 * 删除角色.
	 * 
	 * @param offset
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/role/delete")
	@ResponseBody
	public JsonResponse deleteRole(Long id) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		try {
			result = roleManager.delete(id);
			if (result) {
				jsonResponse.setCode(0);
				jsonResponse.setData(id);
			} else {
				jsonResponse.setMessage(SpringUtils
						.getI18nMessage("webapp.controller.sysError"));
			}
		} catch (ServiceException e) {
			logger.error("Failed to delete role！", e);
			jsonResponse.setMessage(e.getMessage());
		} catch (DataAccessException e) {
			logger.error("Failed to delete role！", e);
			jsonResponse.setMessage(SpringUtils
					.getI18nMessage("webapp.controller.sysError"));
		}

		if (!result) {
			jsonResponse.setCode(1);
		}
		return jsonResponse;
	}

	/**
	 * 修改角色.
	 * 
	 * @param roleRow
	 * @return
	 */
	@RequestMapping(value = "/role/update")
	@ResponseBody
	public JsonResponse updateRole(@Valid UpdateRoleForm updateRoleForm,
			BindingResult validResult) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		// 验证结果检查
		if (validResult.hasErrors()) {
			if (validResult.hasFieldErrors("id")) {
				jsonResponse.setMessage(validResult.getFieldError("id")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("name")) {
				jsonResponse.setMessage(validResult.getFieldError("name")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("displayName")) {
				jsonResponse.setMessage(validResult
						.getFieldError("displayName").getDefaultMessage());
			}
		} else {
			try {
				RoleRow roleRow = roleManager.updateRole(updateRoleForm);
				jsonResponse.setCode(0);
				jsonResponse.setData(roleRow);
				result = true;
			} catch (ServiceException e) {
				logger.error("Failed to update role！", e);
				jsonResponse.setMessage(e.getMessage());
			} catch (DataAccessException e) {
				logger.error("Failed to update role！", e);
				jsonResponse.setMessage(SpringUtils
						.getI18nMessage("webapp.controller.sysError"));
			}
		}

		if (!result) {
			jsonResponse.setCode(1);
		}

		return jsonResponse;
	}

	/**
	 * 添加角色.
	 * 
	 * @param roleRow
	 * @return
	 */
	@RequestMapping(value = "/role/add")
	@ResponseBody
	public JsonResponse addRole(@Valid AddRoleForm addRoleForm,
			BindingResult validResult) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		// 验证结果检查
		if (validResult.hasErrors()) {
			if (validResult.hasFieldErrors("name")) {
				jsonResponse.setMessage(validResult.getFieldError("name")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("displayName")) {
				jsonResponse.setMessage(validResult
						.getFieldError("displayName").getDefaultMessage());
			}
		} else {
			try {
				RoleRow roleRow = roleManager.addRole(addRoleForm);
				jsonResponse.setCode(0);
				jsonResponse.setData(roleRow);
				result = true;
			} catch (ServiceException e) {
				logger.error("Failed to add role！", e);
				jsonResponse.setMessage(e.getMessage());
			} catch (DataAccessException e) {
				logger.error("Failed to add role！", e);
				jsonResponse.setMessage(SpringUtils
						.getI18nMessage("webapp.controller.sysError"));
			}
		}

		if (!result) {
			jsonResponse.setCode(1);
		}

		return jsonResponse;
	}

	/**
	 * 后台权限管理页.
	 * 
	 * @return
	 */
	@RequestMapping(value = "/authority")
	public String authorityListPage() {
		return "admin/authority";
	}

	/**
	 * 获取权限列表.
	 * 
	 * @param offset
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/authority/list")
	@ResponseBody
	public JsonResponse getAuthorityList(int offset, int limit,
			AuthorityCriteria criteria) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		Page<AuthorityRow> authorityList = null;
		try {
			authorityList = authorityManager
					.getAuthoritys(criteria, offset, limit);
			jsonResponse.setCode(0);
			jsonResponse.setData(authorityList);
			result = true;
		} catch (ServiceException e) {
			logger.error("Failed to get authority list！", e);
			jsonResponse.setMessage(e.getMessage());
		} catch (DataAccessException e) {
			logger.error("Failed to get authority list！", e);
			jsonResponse.setMessage(SpringUtils
					.getI18nMessage("webapp.controller.sysError"));
		}

		if (!result) {
			jsonResponse.setCode(1);
			authorityList = new Page<AuthorityRow>();
			authorityList.setTotal(0L);
			authorityList.setRows(null);
			jsonResponse.setData(authorityList);
		}

		return jsonResponse;
	}

	/**
	 * 删除权限.
	 * 
	 * @param offset
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/authority/delete")
	@ResponseBody
	public JsonResponse deleteAuthority(Long id) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		try {
			result = authorityManager.delete(id);
			if (result) {
				jsonResponse.setCode(0);
				jsonResponse.setData(id);
			} else {
				jsonResponse.setMessage(SpringUtils
						.getI18nMessage("webapp.controller.sysError"));
			}
		} catch (ServiceException e) {
			logger.error("Failed to delete authority！", e);
			jsonResponse.setMessage(e.getMessage());
		} catch (DataAccessException e) {
			logger.error("Failed to delete authority！", e);
			jsonResponse.setMessage(SpringUtils
					.getI18nMessage("webapp.controller.sysError"));
		}

		if (!result) {
			jsonResponse.setCode(1);
		}
		return jsonResponse;
	}

	/**
	 * 修改权限.
	 * 
	 * @param authorityRow
	 * @return
	 */
	@RequestMapping(value = "/authority/update")
	@ResponseBody
	public JsonResponse updateAuthority(
			@Valid UpdateAuthorityForm updateAuthorityForm,
			BindingResult validResult) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		// 验证结果检查
		if (validResult.hasErrors()) {
			if (validResult.hasFieldErrors("id")) {
				jsonResponse.setMessage(validResult.getFieldError("id")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("name")) {
				jsonResponse.setMessage(validResult.getFieldError("name")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("displayName")) {
				jsonResponse.setMessage(validResult
						.getFieldError("displayName").getDefaultMessage());
			}
		} else {
			try {
				AuthorityRow authorityRow = authorityManager
						.updateAuthority(updateAuthorityForm);
				jsonResponse.setCode(0);
				jsonResponse.setData(authorityRow);
				result = true;
			} catch (ServiceException e) {
				logger.error("Failed to update authority！", e);
				jsonResponse.setMessage(e.getMessage());
			} catch (DataAccessException e) {
				logger.error("Failed to update authority！", e);
				jsonResponse.setMessage(SpringUtils
						.getI18nMessage("webapp.controller.sysError"));
			}
		}

		if (!result) {
			jsonResponse.setCode(1);
		}

		return jsonResponse;
	}

	/**
	 * 添加权限.
	 * 
	 * @param authorityRow
	 * @return
	 */
	@RequestMapping(value = "/authority/add")
	@ResponseBody
	public JsonResponse addAuthority(@Valid AddAuthorityForm addAuthorityForm,
			BindingResult validResult) {
		JsonResponse jsonResponse = new JsonResponse();
		boolean result = false;
		// 验证结果检查
		if (validResult.hasErrors()) {
			if (validResult.hasFieldErrors("name")) {
				jsonResponse.setMessage(validResult.getFieldError("name")
						.getDefaultMessage());
			} else if (validResult.hasFieldErrors("displayName")) {
				jsonResponse.setMessage(validResult
						.getFieldError("displayName").getDefaultMessage());
			}
		} else {
			try {
				AuthorityRow authorityRow = authorityManager
						.addAuthority(addAuthorityForm);
				jsonResponse.setCode(0);
				jsonResponse.setData(authorityRow);
				result = true;
			} catch (ServiceException e) {
				logger.error("Failed to add authority！", e);
				jsonResponse.setMessage(e.getMessage());
			} catch (DataAccessException e) {
				logger.error("Failed to add authority！", e);
				jsonResponse.setMessage(SpringUtils
						.getI18nMessage("webapp.controller.sysError"));
			}
		}

		if (!result) {
			jsonResponse.setCode(1);
		}

		return jsonResponse;
	}
}
